package com.my.spring.framework.aop.aspect;

import org.apache.commons.collections4.CollectionUtils;

import java.lang.reflect.Method;

public abstract class MyAbstractAspectAdvice implements MyAdvice {
    private Method aspectMethod;
    private Object aspectTarget;

    public MyAbstractAspectAdvice(Method method, Object target) {
        this.aspectMethod = method;
        this.aspectTarget = target;
    }

    public void invokeAdviceMethod(MyJoinPoint joinPoint, Object returnValue, Throwable ex) throws Throwable {
        Class[] paramTypes = aspectMethod.getParameterTypes();
        if (paramTypes.length == 0) {
            aspectMethod.invoke(aspectTarget);
            return;
        }
        Object[] args = new Object[paramTypes.length];
        for (int i = 0; i < paramTypes.length; i++) {
            if (paramTypes[i] == MyJoinPoint.class) {
                args[i] = joinPoint;
            } else if (paramTypes[i] == Throwable.class) {
                args[i] = ex;
            } else if (paramTypes[i] == Object.class) {
                args[i] = returnValue;
            }
        }
        aspectMethod.invoke(aspectTarget, args);
    }
}
